<template>
  <!-- 头部信息 -->
  <HeaderView title="商品详情" :hasBack='true' :path="fromPath"/>

  <div class="content">
    <!-- 产品图 -->
    <div class="img">
      <img src="../../assets/img/9.png" alt=""/>
    </div>

    <!-- 产品描述 -->
    <div class="description">
      <p>{{state.product.title}}</p>
      <p>{{state.product.description}}</p>
      <div class="tag">
        <van-tag type="success" size="medium" plain>推荐</van-tag>
        <van-tag type="success" size="medium" plain>新书</van-tag>
      </div>
      <p>￥{{state.product.price}}.00</p>
      <div class="btn">
        <van-button type="warning" size="mini" @click="addBuy('add')">加入购物车</van-button>
        <van-button type="danger" size="mini" @click="addBuy('buy')">立即购买</van-button>
        <van-button :type='state.product.is_collect === 0 ? "default" : "primary"' size="mini" @click="isCollectProduct">
            {{state.product.is_collect === 0 ? '未收藏' : '收藏'}}
        </van-button>
      </div>
    </div>

    <!-- tab选项卡 -->
    <TabView :details="state.product.details" :recommendProduct="recommendProduct"/>
  </div>

  <!-- 时间超时 -->
  <TimeOutView v-if="timeFlag"/>
</template>

<script lang="ts" setup>
import HeaderView from '@/components/Header/IndexView.vue'
import TabView from './component/TabView.vue'
import TimeOutView from '@/components/TimeOut/IndexView.vue'

import { onMounted, reactive, ref, onActivated } from 'vue'
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { GetDetail, AddCart, IsCollect } from '@/api/detail'
import { GetList } from '@/api/shopcart'
import { UserCollect } from '@/api/mine'
import { CollectNum, ShopcartNum } from '@/pinia/index'

const { saveCollect } = CollectNum()
const { saveNum } = ShopcartNum()
const route = useRoute()
const router = useRouter()
const fromPath = ref('') // 从哪个页面到详情页的
const recommendProduct = ref([]) // 产品推荐
const timeFlag = ref(false) // 请求超时 显示界面
const state = reactive({
  product: {
    id: 0,
    cover_url: '',
    title: '',
    description: '',
    price: 0,
    is_collect: 0, // 产品是否收藏
    details: ''
  }
})

onMounted(() => { init() })

// 产品信息详情
const init = async () => {
  const res = await GetDetail(route.query.id).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') timeFlag.value = true
  })

  try {
    if (res?.status === 200) {
      state.product = res.data.goods
      recommendProduct.value = res.data.like_goods
    }
  } catch (error) {
    console.log(error)
  }
}

// 加入购物车 或者 购买
const addBuy = async (type: string) => {
  const res = await AddCart({ goods_id: state.product.id, num: 1 }).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '网络异常, 收藏失败, 请稍后再试' })
    }
  })

  const res2 = await GetList('include=goods')

  try {
    if (res?.status === 201 || res?.status === 204) {
      saveNum(res2.data.data.length)
      if (type === 'add') { // 只添加商品 不跳转
        showToast({ type: 'success', message: '加入购物车成功', forbidClick: true, duration: 1000 })
      } else { // 添加商品并跳转到购物车
        showToast({
          type: 'loading',
          message: '跳转中',
          forbidClick: true,
          duration: 1000,
          onClose: () => {
            router.push('/shopcart')
          }
        })
      }
    }
  } catch (error) {
    console.log(error)
  }
}

// 收藏 取消 产品 共同弹框信息
const collectMsg = (msg: string, num: number) => {
  showToast({
    type: 'success',
    message: msg,
    forbidClick: true,
    duration: 1500,
    onClose: () => {
      saveCollect(num)
    }
  })
}

// 收藏产品
const isCollectProduct = async () => {
  const res = await IsCollect(state.product.id).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '网络异常, 收藏失败, 请稍后再试' })
    }
  })

  const res2 = await UserCollect()

  try {
    if (res?.status === 201) {
      state.product.is_collect = 1
      collectMsg('收藏成功', res2.data.data.length)
    }
    if (res?.status === 204) {
      state.product.is_collect = 0
      collectMsg('取消收藏', res2.data.data.length)
    }
  } catch (error) {
    console.log(error)
  }
}

// 缓存激活事件 因为详情页被缓存了, 只有产品ID发生变化的时候才重新发起异步请求
onActivated(() => {
  window.scrollTo(0, 0)
  fromPath.value = route.query.fromPath // 记录下是从哪个页面进入到的详情页, 然后好返回
  if (state.product.id !== parseInt(route.query.id)) {
    init()
  }
  state.product.id = parseInt(route.query.id)
})

</script>

<script lang="ts">
export default {
  name: 'detailView'
}
</script>

<style lang="scss" scoped>
.content{
   margin-top: 56px;
   .img{
      text-align: center;
   }
   .description{
      background-color: #fafafa;
      font-size: 14px;
      padding: 10px;
      margin: 10px 0;
      p, .tag{
        margin-bottom: 6px;
      }
      .tag span{
        margin-right: 6px;
      }
      .btn{
        display: flex;
        justify-content: flex-end;
      }
   }
}
</style>
